'''
Created on 2011-05-12

@author: quermit
'''
import json
import logging
import pickle
import base64
import xmlrpclib

from PyQt4.QtCore import QThread
from PyQt4.QtCore import pyqtSignal


log = logging.getLogger(__name__)


class HistoryReader(QThread):

    onMessage = pyqtSignal(object)

    def __init__(self, parent, host, port, index_name, count=200):
        super(HistoryReader, self).__init__(parent)
        self.__host = host
        self.__port = port
        self.__index_name = index_name
        self.__count = count

    def run(self):
        try:
            log.info("Connecting: %s:%d" % (self.__host, self.__port))
            client = xmlrpclib.ServerProxy('http://%s:%d' % (self.__host, self.__port))
        except xmlrpclib.Error, e:
            log.error("XMLRPC Error: %s" % e)
            return

        try:
            log.info("Requesting history...")
            message_list = pickle.loads(base64.decodestring(client.last(self.__count)))
            log.debug("new messages: %d" % len(message_list))
            for msg in message_list:
                self.__handle_message(msg)
        except xmlrpclib.Error, e:
            log.error("XMLRPC Error: %s" % e)
        else:
            log.info("Done")

    def __handle_message(self, msg):
        if not msg:
            return
        try:
            body = json.loads(msg)
        except ValueError, e:
            log.warning("Message parse error: %s" % e)
        else:
            body['origin_index'] = self.__index_name
            self.onMessage.emit(body)

